package com.tianxinweb.exception;

import com.tianxinweb.entity.Result;
import com.tianxinweb.enums.ResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MultipartException;

/**
 * Created by cboy on 2018/1/23.
 */
@RestControllerAdvice
public class ExceptionHandle {

    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value=Exception.class)
    public Result handle(Exception e){
        if(e instanceof MyException){
            MyException myException = (MyException) e;
            return Result.fail(myException.getCode(),myException.getMessage());
        }
        if(e instanceof HttpRequestMethodNotSupportedException){
            return Result.fail(ResultEnum.REQUEST_ERROR.getCode(),ResultEnum.REQUEST_ERROR.getMsg());
        }
        if(e instanceof MissingServletRequestParameterException){
            return Result.fail(ResultEnum.MISSING_PARAMETER_ERROR.getCode(),ResultEnum.MISSING_PARAMETER_ERROR.getMsg());
        }
        if(e instanceof MethodArgumentTypeMismatchException){
            return Result.fail(ResultEnum.PARAMETER_FORMAT_ERROR.getCode(),ResultEnum.PARAMETER_FORMAT_ERROR.getMsg());
        }
        if(e instanceof HttpMessageNotReadableException){
            return Result.fail(ResultEnum.PARAMETER_FORMAT_ERROR.getCode(),ResultEnum.PARAMETER_FORMAT_ERROR.getMsg());
        }
        if(e instanceof HttpMediaTypeNotSupportedException){
            return Result.fail(ResultEnum.REQUEST_ERROR.getCode(),ResultEnum.REQUEST_ERROR.getMsg());
        }
        if(e instanceof MultipartException){
            return Result.fail(ResultEnum.FILE_SIZE_ERROR.getCode(),ResultEnum.FILE_SIZE_ERROR.getMsg());
        }
        logger.error("【系统异常】{}",e);
        return Result.fail(ResultEnum.UNKNONW_ERROR.getCode(),ResultEnum.UNKNONW_ERROR.getMsg());
    }
}
